<template>
  <div ref="echartDivRef" class="base-echart"
    :style="{ width: vw(style.width) + 'vw', height: vh(props.style.height) + 'vh' }" v-resizeEchart="sizeChange">
  </div>
</template>

<script setup>
import { ref, onMounted, watchEffect } from "vue";
import { useEchart } from "../hooks/use-echart";
import * as echarts from "echarts";
import { useDesign } from "@/hooks/use-design/use-design";

const emits = defineEmits(["clickEchart"])

const props = defineProps({
  auto: {
    type: Boolean,
    default: true
  },
  options: {},
  style: {
    type: Object,
    default: () => ({
      width: 0,
      height: 200
    })
  }
})

const echartDivRef = ref();

// 手动更新
let echart = null;

onMounted(() => {
  if (props.auto) {
    init()
  }
});

// 手动初始化echart
const manualInit = (config) => {
  echarts.registerMap(config.name, config.json);
  init()
}

// 自动初始化
const init = () => {
  echart = initEchart(echartDivRef.value);
  echart.on('click', params => {
    emits('clickEchart', params)
  })
  updateOption();
}

// 更新图表配置项
const updateOption = () => {
  watchEffect(() => {
    setOptions(props.options);
  });
};

// 手动更新
const manualUpdate = (options) => {
  if (!echart) {
    echart = initEchart(echartDivRef.value);
  }
  setOptions(options);
};

// 获取echart图片
const getEchartImage = () => {
  if (!echart && echartDivRef.value) {
    echart = initEchart(echartDivRef.value);
  }
  if (!echart) return null;
  echart.resize();
  echart.setOption(props.options, true);
  return echart.getDataURL({
    type: 'png',
    pixelRatio: 2,
    backgroundColor: '#fff'
  });
}

// 监听echart 宽高变化
const sizeChange = (ele) => {
  updateSize();
};

const { initEchart, setOptions, updateSize } = useEchart();

const { vw, vh } = useDesign()

defineExpose({ manualInit, manualUpdate, getEchartImage })
</script>
<style scoped>
.base-echart {
  /* background-color: azure; */
}
</style>